<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>热门板块行情</title>
</head>
<body>
    <div class="container">
        <h2 class="title">热门板块行情</h2>
        <div class="search-box">
            <button class="search-btn" onclick="handleSearch()">获取热门板块数据</button>
        </div>
        <div class="data-container" id="sectorData"></div>
    </div>

    <script>
        let callbackCounter = 0;
        let sectorDataMap = {};

        // 获取最近5个交易日的日期范围
        function getDateRange() {
            const end = new Date();
            const start = new Date();
            start.setDate(start.getDate() - 10);

            return {
                from: formatDate(start),
                to: formatDate(end)
            };
        }

        // 格式化日期为YYYY-MM-DD
        function formatDate(date) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            return `${year}-${month}-${day}`;
        }

        // 创建JSONP回调函数
        function createJsonpCallback(callback) {
            const callbackName = `jsonpCallback_${callbackCounter++}`;
            window[callbackName] = function(data) {
                callback(data);
                delete window[callbackName];
            };
            return callbackName;
        }

        // 使用JSONP获取数据
        function jsonpRequest(url, callback) {
            const callbackName = createJsonpCallback(callback);
            const script = document.createElement('script');
            // 添加callback参数到URL
            url = url.includes('?') ? `${url}&callback=${callbackName}` : `${url}?callback=${callbackName}`;
            script.src = url;
            script.onerror = () => {
                callback(null);
                delete window[callbackName];
            };
            document.body.appendChild(script);
        }

        // 获取热门板块列表
        function fetchHotSectors() {
            return new Promise((resolve, reject) => {
                const url = 'https://vip.stock.finance.sina.com.cn/quotes_service/api/json_v2.php/Market_Center.getHQNodeData?page=1&num=10&sort=changepercent&asc=0&node=bk_name&symbol=';
                
                jsonpRequest(url, (data) => {
                    if (!data || !Array.isArray(data) || data.length === 0) {
                        console.error('获取板块数据失败:', data);
                        reject(new Error('获取板块数据失败'));
                        return;
                    }

                    const sectors = data.map(item => ({
                        code: item.code,
                        name: item.name
                    }));
                    console.log('获取到的板块数据:', sectors);
                    resolve(sectors);
                });
            });
        }

        // 处理查询按钮点击
        async function handleSearch() {
            // 清空之前的数据
            sectorDataMap = {};
            document.getElementById('sectorData').innerHTML = '<div class="loading">数据加载中...</div>';

            try {
                // 获取热门板块列表
                const hotSectors = await fetchHotSectors();
                console.log('准备处理的板块列表:', hotSectors);
                
                if (!hotSectors || hotSectors.length === 0) {
                    throw new Error('未获取到板块数据');
                }
                
                // 获取每个板块的数据
                hotSectors.forEach(sector => {
                    const formattedCode = sector.code.replace('bk_', '');
                    console.log(`开始获取板块数据: ${sector.name}(${formattedCode})`);
                    fetchSectorData(formattedCode, sector.name);
                });
            } catch (error) {
                console.error('处理数据错误:', error);
                document.getElementById('sectorData').innerHTML = '<div class="error">获取板块数据失败，请稍后重试</div>';
            }
        }

        // 生成Markdown格式的数据
        function generateMarkdown(sectorDataMap) {
            const now = new Date();
            const markdownParts = [];
            
            // 添加标题和生成时间
            markdownParts.push(`# 热门板块行情数据`);
            markdownParts.push(`\n生成时间：${formatDate(now)} ${now.toLocaleTimeString()}\n`);
            markdownParts.push(`\n## 当前热门板块\n`);

            // 只输出板块名称列表
            Object.entries(sectorDataMap).forEach(([code, data]) => {
                if (data && data.name) {
                    markdownParts.push(`- ${data.name}`);
                }
            });

            return markdownParts.join('\n');
        }

        // 创建动态回调函数
        function createCallback(sectorCode, sectorName) {
            const callbackName = `jsonpCallback_${callbackCounter++}`;
            window[callbackName] = function(data) {
                if (data && data.length > 0) {
                    // 按日期排序，最新日期在前
                    sectorDataMap[sectorCode] = {
                        data: data.sort((a, b) => new Date(b.day) - new Date(a.day)),
                        name: sectorName
                    };
                } else {
                    sectorDataMap[sectorCode] = {
                        data: null,
                        name: sectorName
                    };
                }
                displayAllData();

                // 当所有板块数据都获取完成时，输出Markdown
                const allSectorsLoaded = Object.keys(sectorDataMap).length === 10;
                if (allSectorsLoaded) {
                    const markdown = generateMarkdown(sectorDataMap);
                    console.log('Markdown格式的数据：\n\n' + markdown);
                }

                // 清理回调函数
                delete window[callbackName];
            };
            return callbackName;
        }

        // 获取板块数据
        function fetchSectorData(sectorCode, sectorName) {
            // 清除之前的script标签
            const oldScript = document.getElementById(`jsonp-script-${sectorCode}`);
            if (oldScript) {
                oldScript.remove();
            }

            const baseUrl = 'https://quotes.sina.cn/cn/api/jsonp_v2.php';
            const callback = createCallback(sectorCode, sectorName);
            const dateRange = getDateRange();
            const params = {
                symbol: `bk_${sectorCode}`,
                scale: 240,
                ma: 'no',
                datalen: 10,
                from: dateRange.from,
                to: dateRange.to
            };

            const url = `${baseUrl}/${callback}/CN_MarketDataService.getKLineData?${new URLSearchParams(params)}`;
            
            const script = document.createElement('script');
            script.id = `jsonp-script-${sectorCode}`;
            script.src = url;
            script.onerror = function() {
                console.error(`获取板块 ${sectorName}(${sectorCode}) 数据失败`);
                sectorDataMap[sectorCode] = {
                    data: 'error',
                    name: sectorName
                };
                displayAllData();
            };
            
            document.body.appendChild(script);
        }

        // 格式化数字为带两位小数的字符串
        function formatNumber(num) {
            return parseFloat(num).toFixed(2);
        }

        // 计算涨跌幅
        function calculateChange(current, previous) {
            if (!previous) return '-';
            const change = ((current - previous) / previous * 100);
            return change > 0 ? `+${change.toFixed(2)}%` : `${change.toFixed(2)}%`;
        }

        // 获取涨跌幅对应的颜色类名
        function getChangeColorClass(changePercent) {
            if (!changePercent || changePercent === '-') return '';
            const change = parseFloat(changePercent);
            if (change > 3) return 'strong-up';
            if (change > 0) return 'up';
            if (change < -3) return 'strong-down';
            if (change < 0) return 'down';
            return '';
        }

        // 显示所有板块数据
        function displayAllData() {
            const container = document.getElementById('sectorData');
            const sectorCards = Object.entries(sectorDataMap).map(([code, sectorInfo]) => {
                const { data, name } = sectorInfo;

                if (!data) {
                    return `
                        <div class="sector-card error">
                            <h3>${name}</h3>
                            <p>暂无数据</p>
                        </div>
                    `;
                }
                if (data === 'error') {
                    return `
                        <div class="sector-card error">
                            <h3>${name}</h3>
                            <p>获取数据失败</p>
                        </div>
                    `;
                }

                // 只取前5个交易日的数据
                const recentData = data.slice(0, 5);
                
                // 计算整体涨跌幅
                const overallChange = calculateChange(
                    recentData[0].close,
                    recentData[recentData.length - 1].close
                );
                const overallChangeClass = getChangeColorClass(overallChange);

                // 生成数据行
                const dataRows = recentData.map((day, index) => {
                    const changePercent = calculateChange(
                        day.close,
                        index < recentData.length - 1 ? recentData[index + 1].close : null
                    );
                    const changeClass = getChangeColorClass(changePercent);
                    
                    return `
                        <tr class="${changeClass}">
                            <td>${day.day}</td>
                            <td>${formatNumber(day.open)}</td>
                            <td>${formatNumber(day.close)}</td>
                            <td>${formatNumber(day.high)}</td>
                            <td>${formatNumber(day.low)}</td>
                            <td>${changePercent}</td>
                            <td>${(day.volume / 100000000).toFixed(2)}亿</td>
                        </tr>
                    `;
                }).join('');

                return `
                    <div class="sector-card ${overallChangeClass}">
                        <h3>${name}</h3>
                        <div class="sector-info">
                            <table class="data-table">
                                <thead>
                                    <tr>
                                        <th>日期</th>
                                        <th>开盘</th>
                                        <th>收盘</th>
                                        <th>最高</th>
                                        <th>最低</th>
                                        <th>涨跌幅</th>
                                        <th>成交量</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    ${dataRows}
                                </tbody>
                            </table>
                        </div>
                    </div>
                `;
            }).join('');

            container.innerHTML = sectorCards;
        }
    </script>

    <style>
        .container {
            max-width: 1200px;
            margin: 20px auto;
            padding: 20px;
            font-family: Arial, sans-serif;
        }
        
        .title {
            text-align: center;
            color: #333;
            margin-bottom: 30px;
        }

        .search-box {
            margin-bottom: 30px;
            text-align: center;
        }

        .search-btn {
            padding: 10px 30px;
            background-color: #2196F3;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
        }

        .search-btn:hover {
            background-color: #1976D2;
        }

        .data-container {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(600px, 1fr));
            gap: 20px;
        }

        .sector-card {
            background-color: #fff;
            padding: 15px;
            border-radius: 5px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            transition: all 0.3s ease;
        }

        .sector-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.15);
        }

        .sector-card h3 {
            margin: 0 0 15px 0;
            color: #333;
            font-size: 18px;
        }

        .data-table {
            width: 100%;
            border-collapse: collapse;
            font-size: 14px;
        }

        .data-table th,
        .data-table td {
            padding: 8px;
            text-align: right;
            border-bottom: 1px solid #eee;
        }

        .data-table th:first-child,
        .data-table td:first-child {
            text-align: left;
        }

        .data-table thead th {
            background-color: #f5f5f5;
            font-weight: bold;
        }

        /* 涨跌颜色样式 */
        .strong-up {
            background-color: #ffebee;
        }

        .up {
            background-color: #ffebee;
            opacity: 0.7;
        }

        .strong-down {
            background-color: #e8f5e9;
        }

        .down {
            background-color: #e8f5e9;
            opacity: 0.7;
        }

        tr.strong-up td {
            color: #d32f2f;
        }

        tr.up td {
            color: #e53935;
        }

        tr.strong-down td {
            color: #2e7d32;
        }

        tr.down td {
            color: #43a047;
        }

        .error {
            background-color: #fff3f3;
            color: #d63031;
            text-align: center;
        }

        .loading {
            text-align: center;
            padding: 20px;
            font-size: 16px;
            color: #666;
        }

        @media (max-width: 768px) {
            .data-container {
                grid-template-columns: 1fr;
            }
            
            .data-table {
                font-size: 12px;
            }
            
            .data-table th,
            .data-table td {
                padding: 6px 4px;
            }
        }
    </style>
</body>
</html> 